﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Aurora.AI.Common.Constants;
using Aurora.AI.Domain.Domain.Setting.Aggregates;
using Aurora.Redis;
using System.Collections.Immutable;
using System.Text.Json;
using Aurora.AI.SqlSugar.Framework.Repositories;
using Aurora.AI.Gateway.Models.Setting;
using Aurora.AI.Common.Extensions;
using Aurora.AI.Common.Models;

namespace Aurora.AI.Gateway.Services;

/// <summary>
/// 配置服务 open ai
/// </summary>
public class SettingService(IRepository<Setting> repository, IRedisCache redisCache)
{
    /// <summary>
    /// 更新ai 设置
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task Update(AISettingRequest request)
    {
        if (!string.IsNullOrEmpty(request.Prompt))
        {
            // 更新 prompt 
            await UpdateSettingsAsync("Setting:ModelPromptRate", request.Prompt);
            await redisCache.DelAsync(CacheConstant.PromptRateCacheKey);
        }

        if (!string.IsNullOrEmpty(request.Completion))
        {
            // 更新 Completion 
            await UpdateSettingsAsync("Setting:ModelCompletionRate", request.Completion);
            await redisCache.DelAsync(CacheConstant.CompletionRateCacheKey);
        }

        if (request.Common != null)
        {
            await UpdateSettingsAsync("Setting:Common", AuroraAIJsonSerializer.Serialize(request.Common));
        }
    }

    public async Task<AISettingRequest> GetJson()
    {
        AISettingRequest request = new AISettingRequest();

        var data = await GetAllAsync();
        var prompt = data.FirstOrDefault(x => x.Key.Equals("Setting:ModelPromptRate"));
        if (prompt != null)
        {
            request.Prompt = prompt.Value;
        }

        var completion = data.FirstOrDefault(x => x.Key.Equals("Setting:ModelCompletionRate"));
        if (completion != null)
        {
            request.Completion = completion.Value;
        }

        var common = data.FirstOrDefault(x => x.Key.Equals("Setting:Common"));
        if (common != null)
        {
            request.Common = AuroraAIJsonSerializer.Deserialize<AICommonSetting>(common.Value);
        }


        return request;
    }

    /// <summary>
    /// 模型倍率Prompt
    /// </summary>
    /// <returns></returns>
    public async Task<Dictionary<string, decimal>> GetPromptRate()
    {
        return await GetSetting<Dictionary<string, decimal>>("Setting:ModelPromptRate");
    }

    /// <summary>
    /// 模型倍率Completion
    /// </summary>
    /// <returns></returns>
    public async Task<Dictionary<string, decimal>> GetCompletionRate()
    {
        return await GetSetting<Dictionary<string, decimal>>("Setting:ModelCompletionRate");
    }

    /// <summary>
    /// 获取通用的 ai 设置
    /// </summary>
    /// <returns></returns>
    public async Task<AICommonSetting> GetCommonSetting()
    {
        string key = CacheConstant.CommonSettingCacheKey;
        AICommonSetting aiCommonSetting = await redisCache.GetAsync<AICommonSetting>(key);
        if (aiCommonSetting != null)
            return aiCommonSetting;
        AICommonSetting commonSetting = await GetSetting<AICommonSetting>("Setting:Common");
        await redisCache.AddAsync(key, commonSetting, TimeSpan.FromHours(24));
        return commonSetting;
    }

    /// <summary>
    /// 获取所有的
    /// </summary>
    /// <returns></returns>
    public async Task<List<Setting>> GetAllAsync()
    {
        return await repository.GetListAsync(x => x.IsDeleted == false);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<string> GetSettingByKey(string key)
    {
        return (await repository.GetFirstAsync(x => x.Key == key))?.Value ?? string.Empty;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<T> GetSetting<T>(string key)
    {
        var value = await GetSettingByKey(key);
        return string.IsNullOrEmpty(value) ? default : JsonSerializer.Deserialize<T>(value);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<int> GetIntSetting(string key)
    {
        var value = await GetSettingByKey(key);
        return string.IsNullOrEmpty(value) ? 0 : int.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<bool> GetBoolSetting(string key)
    {
        var value = await GetSettingByKey(key);
        return !string.IsNullOrEmpty(value) && bool.TryParse(value, out var result) && result;
    }


    /// <summary>
    /// 如果是管理员，返回所有设置，否则返回公开的设置
    /// </summary>
    /// <param name="userContext"></param>
    /// <returns></returns>
    public async Task<ImmutableList<Setting>> GetSettings(bool isAdmin)
    {
        return isAdmin
            ? (await GetAllAsync()).ToImmutableList()
            : (await repository.GetListAsync(x => x.Private == false)).ToImmutableList();
    }


    /// <summary>
    /// 更新设置
    /// </summary>
    /// <param name="settings"></param>
    /// <param name="dbContext"></param>
    public async ValueTask UpdateSettingsAsync(List<Setting> settings)
    {
        var dbSettings = await GetAllAsync();
        foreach (var setting in dbSettings)
        {
            var newSetting = settings.FirstOrDefault(x => x.Key == setting.Key);
            if (newSetting != null)
            {
                setting.Value = newSetting.Value;
                setting.ModificationTime = DateTime.Now;
            }
        }

        await repository.UpdateRangeAsync(dbSettings);
    }

    /// <summary>
    /// 更新设置
    /// </summary>
    /// <param name="settings"></param>
    /// <param name="dbContext"></param>
    public async ValueTask UpdateSettingsAsync(string key, string value)
    {
        var dbSettings = await repository.GetFirstAsync(x => x.Key.Equals(key));
        if (dbSettings != null)
        {
            dbSettings.Value = value;
            dbSettings.ModificationTime = DateTime.Now;
            await repository.UpdateAsync(dbSettings);
            await redisCache.DelAsync(key);
        }
    }


    /// <summary>
    /// 获取图片速率
    /// </summary>
    /// <returns></returns>
    public Task<Dictionary<string, Dictionary<string, double>>> GetImageSizeRatios()
    {
        return Task.FromResult(new Dictionary<string, Dictionary<string, double>>()
        {
            {
                "dall-e-2", new Dictionary<string, double>
                {
                    { "256x256", 1 },
                    { "512x512", 1.125 },
                    { "1024x1024", 1.25 }
                }
            },
            {
                "dall-e-3", new Dictionary<string, double>
                {
                    { "1024x1024", 1 },
                    { "1024x1792", 2 },
                    { "1792x1024", 2 }
                }
            },
            {
                "ali-stable-diffusion-xl", new Dictionary<string, double>
                {
                    { "512x1024", 1 },
                    { "1024x768", 1 },
                    { "1024x1024", 1 },
                    { "576x1024", 1 },
                    { "1024x576", 1 }
                }
            },
            {
                "ali-stable-diffusion-v1.5", new Dictionary<string, double>
                {
                    { "512x1024", 1 },
                    { "1024x768", 1 },
                    { "1024x1024", 1 },
                    { "576x1024", 1 },
                    { "1024x576", 1 }
                }
            },
            {
                "wanx-v1", new Dictionary<string, double>
                {
                    { "1024x1024", 1 },
                    { "720x1280", 1 },
                    { "1280x720", 1 }
                }
            }
        });
    }


    /// <summary>
    /// 获取速率
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<decimal?> GetPromptRate(string model)
    {
        var data = await redisCache.GetAsync<Dictionary<string, decimal>>(CacheConstant.PromptRateCacheKey);
        if (data == null)
        {
            data = await GetPromptRate();
            await redisCache.AddAsync(CacheConstant.PromptRateCacheKey, data, TimeSpan.FromHours(24));
        }

        var success = data.TryGetValue(model, out var rate);
        return success ? rate : null;
    }
}